﻿using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using PortalWeb.Business.Entity;
using PortalWeb.Dao;
using PortalWeb.Dao.Base;
using PortalWeb.Service;

namespace PortalWeb.Business.Manager
{

    // 配置此应用程序中使用的应用程序用户管理器。UserManager 在 ASP.NET Identity 中定义，并由此应用程序使用。
    public sealed class ApplicationUserManager : UserManager<ApplicationUserModel, string>, IDisposable
    {
        public ApplicationUserManager(
            UserStore<ApplicationUserModel, ApplicationRoleModel, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
                store)
            : base(store)
        {

        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
            IOwinContext context)
        {
            var manager =
                new ApplicationUserManager(
                    new UserStore
                        <ApplicationUserModel, ApplicationRoleModel, string, IdentityUserLogin, IdentityUserRole,
                            IdentityUserClaim>(context.Get<ApplicationIdentityDbContext>()));
            // 配置用户名的验证逻辑
            manager.UserValidator = new UserValidator<ApplicationUserModel>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // 配置密码的验证逻辑
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // 配置用户锁定默认值
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 注册双重身份验证提供程序。此应用程序使用手机和电子邮件作为接收用于验证用户的代码的一个步骤
            // 你可以编写自己的提供程序并将其插入到此处。
            manager.RegisterTwoFactorProvider("电话代码", new PhoneNumberTokenProvider<ApplicationUserModel>
            {
                MessageFormat = "你的安全代码是 {0}"
            });
            manager.RegisterTwoFactorProvider("电子邮件代码", new EmailTokenProvider<ApplicationUserModel>
            {
                Subject = "安全代码",
                BodyFormat = "你的安全代码是 {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUserModel>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }

        [DebuggerStepThrough]
        public async Task<ApplicationUserModel[]> LoadPageEntitiesnAsync<TS>(
            Expression<Func<ApplicationUserModel, bool>> whereLambda, string order, string sort, int offset, int limit)
        {
            this.ThrowIfDisposed();
            return await Users.Where(whereLambda)
                .OrderBy(sort + " " + order).Skip(offset)
                .Take(limit - offset)
                .ToArrayAsync();
        }


        [DebuggerStepThrough]
        public async Task<ApplicationUserModel[]> LoadEntitiesnAsync<TS>(
            Expression<Func<ApplicationUserModel, bool>> whereLambda)
        {
            this.ThrowIfDisposed();
            return await Users.Where(whereLambda).ToArrayAsync();
        }

        private void ThrowIfDisposed()
        {
            if (this._disposed)
            {
                throw new ObjectDisposedException(base.GetType().Name);
            }
        }

        private bool _disposed;

        protected override void Dispose(bool disposing)
        {
            if (disposing && !this._disposed)
            {
                this.Store.Dispose();
                this._disposed = true;
            }
        }
    }
}